<template>
    <div class="publish-aritcle">
        <p class="page-title"><i class="el-icon-edit-outline"></i>发布文章</p>
        <div class="publish-form">
          <el-form status-icon :rules="rules" ref="publishForm" :model="publishForm">
            <el-form-item>
              <el-row :style="'width:'+screenHeigth+''">
                <el-alert
                  title="温馨提示：请勿发布、传播违反国家法律法规以及翻墙类内容！"
                  type="error"
                  effect="dark">
                </el-alert>
              </el-row>
            </el-form-item>
            <el-form-item prop="title">
              <el-row :style="'width:'+screenHeigth+''">
                <el-input v-model="publishForm.title" type="text" show-word-limit placeholder="请输入文章标题" autocomplete="off" maxlength="60"></el-input>
              </el-row>
            </el-form-item>
            <el-form-item >
              <el-row :style="'width:'+screenHeigth+''">
                <!--编辑器 -->
                <quill-editor
                v-model="publishForm.content"
                ref="myQuillEditor"
                :options="editorOption"
                @change="onEditorChange($event)">
                </quill-editor>
                <!-- 图片上传组件辅助-->
                <el-upload
                class="avatar-uploader"
                :action="serverUrl"
                name="file"
                :show-file-list="false"
                :on-success="uploadSuccess"
                :on-error="uploadError"
                :with-credentials="true"
                :data="{type:2}">
                </el-upload>
              </el-row>
            </el-form-item>

            <el-form-item label="关  键  字：" prop="keyWordArray">
              <el-row :style="'width:'+screenHeigth+''">
                <el-tag
                  :key="tag"
                  v-for="tag in publishForm.keyWordArray"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag)">
                  {{tag}}
                </el-tag>
                <el-input
                  type="text"
                  class="input-new-tag"
                  v-if="inputVisible==2"
                  v-model="inputTag"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm"
                  @blur="handleInputConfirm" maxlength="10" show-word-limit></el-input>
                <el-button v-else-if="inputVisible==1" class="button-new-tag" size="small" @click="showInput">+ 添加关键字</el-button>
              </el-row>
            </el-form-item>

            <el-form-item label="上传封面：" prop="cover">
              <el-row :style="'width:'+screenHeigth+''">
                <el-upload
                  :multiple="false"
                  :limit="1"
                  :action="serverUrl"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :on-success="UploadCoverSuccess"
                  :on-error="uplodaCoverError"
                  ref="coverUpload"
                  :with-credentials="true"
                  :data="{type:1}">
                 <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                  <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
              </el-row>
            </el-form-item>


            <el-form-item label="添加水印：">
              <el-row :style="'width:'+screenHeigth+''">
                <el-switch
                  v-model="publishForm.watemark"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
                </el-switch>
              </el-row>
            </el-form-item>
            
            <el-form-item label="开启评论：">
              <el-row :style="'width:'+screenHeigth+''">
                <el-switch
                  v-model="publishForm.canComment"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
                </el-switch>
              </el-row>
            </el-form-item>

            <el-form-item label="文章分类：" prop="artType">
              <el-row :style="'width:'+screenHeigth+''">
                <el-select v-model="publishForm.artType" placeholder="请选择">
                    <el-option
                    v-for="item in options"
                    :key="item.artType"
                    :label="item.artType"
                    :value="item.artType">
                    </el-option>
                </el-select>
              </el-row>
            </el-form-item>

            <el-form-item label="文章类型：" prop="publisType">
              <el-row :style="'width:'+screenHeigth+''">
                <el-select v-model="publishForm.publisType" placeholder="请选择">
                  <el-option label="原创" value="1"></el-option>
                  <el-option label="转载" value="2"></el-option>
                </el-select>
              </el-row>
            </el-form-item>

            <el-form-item>
              <el-row :style="'width:'+screenHeigth+''">
                <div class="publish-button">
                  <el-button type="success" @click="submitForm('publishForm')">立即发布</el-button>
                  <el-button type="danger" @click="PreviewMethod()">&nbsp;&nbsp;&nbsp;&nbsp;预览&nbsp;&nbsp;&nbsp;&nbsp;</el-button>
                </div>
              </el-row>
            </el-form-item>

          </el-form>
        </div>
        <el-dialog :visible.sync="Preview" top="0vh">
          <h3 class="preview-title">{{this.publishForm.title}}</h3>
          <div class="preview-content" v-html="this.publishForm.content">
          </div>
        </el-dialog>
    </div>
</template>
<script>
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
  [{'list': 'ordered'}, 
  {'list': 'bullet'}],
  [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
  [{'header': [1, 2, 3, 4, 5, 6, false]}],
  [{'color': []}, 
  {'background': []}],          // dropdown with defaults from theme
  [{'align': []}],
  ['link', 'image'],
  ['clean']
];
import index_top from '@/blog/index/index_top'
import { post,fetch } from '@/utils/httpRequest'
export default {
  components:{
    index_top
  },
  data(){
     var validateTitle = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入标题'));
        } else {
          callback();
        }
    };
    var validateArtType = (rule, value, callback) => {
        if (value === undefined||value === "") {
          callback(new Error('请选择文章分类'));
        } else {
          callback();
        }
    };
    var validatePublisType = (rule, value, callback) => {
        if (value === undefined||value === "") {
          callback(new Error('请选择文章类型'));
        } else {
          callback();
        }
    };
    var validateKeyWord = (rule, value, callback) => {
        if (this.publishForm.keyWordArray.length === 0) {
          callback(new Error('请输入关键字'));
        } else {
          callback();
        }
    };
    var validateCover=(rule, value, callback) => {
        if (this.publishForm.cover === '') {
          callback(new Error('请上传封面'));
        } else {
          callback();
        }
    };
    return {
      editorOption: {
        placeholder: '',
        theme: 'snow',  // or 'bubble'
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: {
              'image': function (value) {
                if (value) {
                  // 触发input框选择图片文件
                  document.querySelector('.avatar-uploader input').click()
                } else {
                  this.quill.format('image', false);
                }
              }
            }
          }
        }
      },
      serverUrl: this.http.host+this.http.blog_article.article.image_upload,  // 这里写你要上传的图片服务器地址
      publishForm:{
        title: "",
        content: null,
        keyWords: "",
        watemark: true,
        canComment: true,
        publisType:"",
        artType:"",
        cover:"",
        keyWordArray: [],
      },
      options: [],
        rules: {
          title: [  
            { validator: validateTitle, trigger: 'blur' }
          ],
          artType: [
            { validator: validateArtType, trigger: 'change' }
          ],
          publisType:[
             { validator: validatePublisType, trigger: 'change' }
          ],
          keyWordArray:[
            { validator: validateKeyWord, trigger: 'click' }
          ],
          cover:[
            { validator: validateCover, trigger: 'click' }
          ]
        },
        inputVisible: 1,
        inputTag:'',
        dialogImageUrl: '',
        dialogVisible: false,
        Preview : false,
        screenHeigth:document.body.clientWidth<500?document.body.clientWidth-20+"px":'100%'
      }
  },  
  methods: {
    onEditorChange({editor, html, text}) {//内容改变事件
      this.publishForm.content = html;
    },
    uploadSuccess(res, file) {
      let quill = this.$refs.myQuillEditor.quill
      if (res.success === true ) {
        let length = quill.getSelection().index;
        quill.insertEmbed(length, 'image', res.data.accessPath)
        quill.setSelection(length + 1)
      } else {
        this.$notify.error({
            title: '通知',
            message: '图片上传失败'
        });
      }
    },  
    uploadError() {
      this.$notify.error({
          title: '通知',
          message: '图片上传失败'
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.publishForm.content===null ||this.publishForm.content.length<300){
            this.$notify.error({
              title: '通知',
              message: '正文长度不能小于300'
            });
            return false;
          }
          // 发布文章
          this.publishArticle(this.publishForm);
        } else {
          return false;
        }
      });
    },
    showInput() {
        this.inputVisible = 2;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    handleInputConfirm() {
      let inputTag = this.inputTag;
      if (inputTag) {
        this.publishForm.keyWordArray.push(inputTag);
        if(this.publishForm.keyWordArray.length>=2){
          this.inputTag = '';
          this.inputVisible = 3;
          return;
        }
      }
      this.inputVisible = 1;
      this.inputTag = '';
    },
    handleClose(tag) {
      this.publishForm.keyWordArray.splice(this.publishForm.keyWordArray.indexOf(tag), 1);
      if(this.publishForm.keyWordArray.length<2){
          this.inputVisible = 1;
          return;
      }
    },
    handleRemove(file, fileList) {
      document.querySelector('.el-upload--picture-card').style.display = "inline-block";
      this.cover=""
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.response.data.accessPath;
      this.dialogVisible = true;
    },
    UploadCoverSuccess(res, file){
      if(res.success=== false){
        this.$refs.coverUpload.clearFiles();
        this.$notify.error({
            title: '通知',
            message: res.message
        });
      }else{
        this.publishForm.cover=res.data.accessPath;
        document.querySelector('.el-upload--picture-card').style.display = "none";
      }
    },
    uplodaCoverError(){
      document.querySelector('.el-upload--picture-card').style.display = "inline-block";
      this.$notify.error({
          title: '通知',
          message: '封面上传失败'
      });
    },
    publishArticle(data){
      const loading = this.$loading({
            lock: true,
            text: '发布中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
      });
      this.publishForm.keyWords=JSON.stringify(data.keyWordArray)
      post(this.http.blog_article.article.publishArticle,data).then((response)=>{
        loading.close();
        if(!response.success){
          this.$notify.error({
            title: '通知',
            message: response.message
          });
        }else{
          this.$refs["publishForm"].resetFields();
          this.$refs.coverUpload.clearFiles();
          this.publishForm.cover="";
          this.publishForm.keyWordArray=[];
          document.querySelector('.el-upload--picture-card').style.display = "inline-block";
          this.publishForm.content=null;
        }
      })
    },
    getArticleType(){
      fetch(this.http.blog_article.article.getArticleType,{}).then((response)=>{
          this.options=response.data;
      })
    },
    PreviewMethod(){
      this.Preview=true;
    }
  },
  created:function(){
    if(this.$store.getters.loginData.canPublish===0){
      this.$notify.error({
        title: '通知',
        message: '对不起,您暂时没有发文权限,请找管理员申请开通吧！'
      });
      this.$router.push({path:'/'})
      return;
    }
    this.getArticleType()
  }
}
</script>
<style scoped>
@media screen and (max-width: 500px){
  .el-dialog__wrapper >>> .el-dialog{
    width: 100%
  }
}
.el-form-item  >>> .el-form-item__label{
  color: white;
}
.el-col-4{
  width: 150px; 
}
.el-form-item  >>> .el-form-item__content {
    line-height: 45px;
}
.publish-form{
  margin: 10px;
}
.publish-aritcle{
  width: 100%;
  height: 100%;
}
.preview-title{
  font-weight: bold;
  padding: 10px 0px;
  font-size: 20px;
}
.preview-content >>> img{
  width: 100%;
  height: 100%;
}
.preview-content >>> pre{
    background-color: #23241f;
    color: #f8f8f2;
    overflow: visible;
    white-space: pre-wrap;
    margin-top: 5px;
    padding: 5px 10px;
}
.quill-editor >>> .ql-editor{
  background-color: white;
}
.quill-editor{
  height: 400px;
  background-color: white;
}
.quill-editor img{
  height: 400px;
}
.publish-button{
  text-align: center;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 120px;
  margin-left: 10px;
  vertical-align: bottom;
}
.el-alert{
  padding: 0px;
}
.el-alert >>> .el-alert__title{
  font-size: 10px;
}
.el-alert >>>  .el-alert__closebtn {
    top: 17px;
}
</style>